<?php

namespace Database\Seeders;

use App\Models\Recruit;
use App\Models\RecruitCategory;
use App\Models\User;
use Faker\Factory;
use Faker\Generator;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class RecruitSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
       $this->insert();
    }

    public function insert()
    {
        // 获取 Faker 实例
        $faker = app(Generator::class);

        // 取出所有 user_id
        $users = User::all()->pluck('nickname','id')->toArray();

        // 取出所有分类
        $recruitCategories = RecruitCategory::all()->where('level', '=', 2)->pluck('name', 'id')->toArray();

        // 生成数据集合
        $recruits = Recruit::factory() //factory(User::class) 根据指定的 User 生成模型工厂构造器，对应加载 UserFactory.php 中的工厂设置
        ->times(30)  // 生成 1 个数据
        ->make()            // 将结果生成为 集合对象
        ->each(function ($recruit) use ($faker, $users, $recruitCategories) { //是集合对象提供的方法,用来迭代集合中的内容并将其传递到回调函数中
            $recruit->contact_name = $faker->randomElement($users);
            $recruit->user_id = array_search($recruit->contact_name, $users);
            $recruit->contact_phone = User::query()->where('id', '=', $recruit->user_id)->value('mobile');
            $recruit->recruit_cate_name = $faker->randomElement($recruitCategories);
            $recruit->recruit_cate_id = array_search($recruit->recruit_cate_name, $recruitCategories);
        });

        // 将数据集合转换为数组，并插入到数据库中
        Recruit::query()->insert($recruits->toArray());
    }

    public function update()
    {

    }
}
